<?php
/**
 * Youdian Content Management System
 * Copyright (C) YoudianSoft Co.,Ltd (http://www.youdiancms.com). All rights reserved.
 */
class ChannelAction extends AdminBaseAction {
	function index(){
		header("Content-Type:text/html; charset=utf-8");
		//非超级管理员需要判断权限================
		$gid = session('AdminGroupID');
		$idlist = false;
		if($gid != 1){
			$m = D('Admin/AdminGroup');
			$idlist = $m->getChannelPurview( $gid );
		}
		//=================================
		$c = D('Admin/Channel');
		$channel = $c->getChannelList(0, -1, '', $idlist);
		$count = count( $channel );
		//找出ChannelDepth最大值
		$maxDepth = -9999;
		for($j = 0; $j < $count; $j++){
			if( $channel[$j]['ChannelDepth'] > $maxDepth ) {
				$maxDepth = $channel[$j]['ChannelDepth'];
			}
		}
		
		//归一化频道深度
		for($i = 0; $i < $count; $i++){
			$channel[$i]['ChannelDepth'] = ($maxDepth - $channel[$i]['ChannelDepth'] + 1);
		}
		
		$this->assign('Channel', $channel);
		$this->display();
	}
	
	function add(){
		header("Content-Type:text/html; charset=utf-8");
		//模型属性信息==============================================
		$m = D('Admin/Attribute');
		$Attribute = $m->getAttribute(1);
		$Group = $m->getGroup(1);
		$gid = session('AdminGroupID');
		
		for($n = 0; $n < count($Attribute); $n++){
			if( $this->IsSelectedAttribute( $Attribute[$n]['DisplayType'] ) ){
				if ( $Attribute[$n]['DisplayType'] == 'channelselect'){
					$Attribute[$n]['FirstValue'] = "0"; //FirstValue
					$Attribute[$n]['FirstText'] = "作为主频道"; //FirstText
					$Attribute[$n]['AdminGroupID'] = session('AdminGroupID');
				}
			}
		}
		$Attribute = parent::parseAttribute($Attribute);  //解析属性信息
		//======================================================
		$this->assign('Action', __URL__.'/saveAdd');
		$this->assign('Group', $Group);
		$this->assign('Attribute', $Attribute);
		$this->display();
	}
	
	function batchAdd(){
		header("Content-Type:text/html; charset=utf-8");
		//获取频道信息
		$m1 = D('Admin/Channel');
		$gid = session('AdminGroupID');
		$channel = $m1->getChannel(0,true,true, -1, -1, '&nbsp;&nbsp;&nbsp;&nbsp;├─ ', $gid); //不显示链接频道
		$n = count($channel);
		
		$m2 = D('Admin/ChannelModel');
		$model = $m2->getChannelModel(0,1,true);
		
		$this->assign('Channel', $channel);
		$this->assign('ChannelModel', $model);
		$this->assign('Action', __URL__.'/saveBatchAdd');
		$this->display();
	}
	
	function saveBatchAdd(){
		header("Content-Type:text/html; charset=utf-8");
		$arrParent = $_POST['Parent'];
		$arrChannelName = $_POST['ChannelName'];
		$arrChannelModelID = $_POST['ChannelModelID'];
		$arrChannelOrder = $_POST['ChannelOrder'];
		$arrPageSize = $_POST['PageSize'];
		$arrIndexTemplate = $_POST['IndexTemplate'];
		$arrReadTemplate = $_POST['ReadTemplate'];
		
		$data = array();
		$count = count($arrChannelName);
		for($i = 0; $i<$count; $i++){
			if( $arrChannelName[$i] != ''){
				$data[] = array('ChannelName'=>$arrChannelName[$i],
					'Parent'=>$arrParent[$i],
					'ReadLevel'=>'',
					'ChannelModelID'=>$arrChannelModelID[$i],
					'ChannelOrder'=>$arrChannelOrder[$i],
					'PageSize'=>$arrPageSize[$i],
					'Html'=>yd_pinyin( $arrChannelName[$i] ),
					'ChannelTarget'=>'_self',
					'IndexTemplate'=>$arrIndexTemplate[$i],
					'ReadTemplate' =>$arrReadTemplate[$i],
					'LanguageID'=>get_language_id(),
				);
			}
		}
		if( empty($data) ){
			$this->ajaxReturn(null, '添加失败!' , 0);
		}
		
		$m = D('Admin/Channel');
		if($m->addAll( $data )){
			YdCache::writeConfig(); //清除频道缓存
			WriteLog(implode(',', $arrChannelName));
			$this->ajaxReturn(null, '添加成功!' , 1);
		}else{
			$this->ajaxReturn(null, '添加失败!' , 0);
		}
	}
	
	function saveAdd(){
		header("Content-Type:text/html; charset=utf-8");
		unset($_POST['AlbumTitle'], $_POST['AlbumPicture'], $_POST['AlbumDescription']);
		$n = count($_POST);
		foreach ($_POST as $k=>$v){
			if( is_array($v) ){
				$_POST[$k] = implode(',', $v);
			}
		}
		if( empty($_POST['Html']) ){
			if( function_exists('iconv')){
				$_POST['Html'] = yd_pinyin( $_POST['ChannelName'] );
			}else{
				$this->ajaxReturn(null, "服务器不支持iconv，无法\"生成静态页面名称\"，请录入！" , 0);
			}
		}
		if( !isset($_POST['ReadLevel']) ) $_POST['ReadLevel'] = '';
		if( !isset($_POST['f1']) ) $_POST['f1'] = '';
		if( !isset($_POST['f2']) ) $_POST['f2'] = '';
		if( !isset($_POST['f3']) ) $_POST['f3'] = '';
		
		$_POST['ChannelDepth'] = 1;  //默认为1

		$c = D('Admin/Channel');
		if( $c->create() ){
			if($GLOBALS['Config']['AUTO_UPLOAD_ENABLE']==1 && stripos($c->ChannelContent , '<img') !== false ){
				$temp = yd_upload_content($c->ChannelContent); //自动上传远程图片
				$c->ChannelContent = $temp[2];
			}
			if($c->add()){
				$lastID = $c->getLastInsID();
				if( $_POST['Parent'] != 0){ //等于0表示1即栏目，无需更新频道缓存
					YdCache::writeConfig(); //清除频道缓存
				}
				WriteLog("ID:".$lastID);
				$msg = baidu_push_channel($lastID);
				$this->ajaxReturn(null, "添加频道成功！{$msg}" , 1);
			}else{
				$this->ajaxReturn(null, '添加频道失败！' , 0);
			}
		}else{
			$this->ajaxReturn(null, $c->getError() , 0);
		}
	}
	
	function modify(){
		header("Content-Type:text/html; charset=utf-8");
		//参数有效性检查===========================
		$ChannelID = $_GET['ChannelID'];
		if( !is_numeric($ChannelID)){
			alert("非法参数", __URL__.'/index');
		}
		//====================================
		
		//模型属性信息=================================================
		$m = D('Admin/Attribute');
		$Attribute = $m->getAttribute(1);
		$Group = $m->getGroup(1);
		
		//获取频道数据=====================
		$c = D('Admin/Channel');
		$ChannelInfo = $c->find( $ChannelID );
		for($n = 0; $n < count($Attribute); $n++){
			if( $this->IsSelectedAttribute( $Attribute[$n]['DisplayType'] ) ){
				if ( $Attribute[$n]['DisplayType'] == 'channelselect'){
					$Attribute[$n]['SelectedValue'] = $ChannelInfo[ 'Parent' ]; //获取频道设置值
					$Attribute[$n]['FirstValue'] = "0"; //FirstValue
					$Attribute[$n]['FirstText'] = "作为主频道"; //FirstText
					$Attribute[$n]['ExcludeChannel'] = $ChannelID; //不显示某个频道
					$Attribute[$n]['AdminGroupID'] = session('AdminGroupID');
				}else if($Attribute[$n]['DisplayType'] == 'membergroupcheckbox'){ //会员分组checkbox
					$Attribute[$n]['DisplayValue'] = $ChannelInfo[ $Attribute[$n]['FieldName'] ];
				}else{
					$Attribute[$n]['SelectedValue'] = $ChannelInfo[ $Attribute[$n]['FieldName'] ]; //获取频道设置值
				}
			}else{
				$Attribute[$n]['DisplayValue'] = $ChannelInfo[ $Attribute[$n]['FieldName'] ];
			}
		}
		
		$Attribute = parent::parseAttribute($Attribute);  //解析属性信息
		//=========================================================
		
		$this->assign('ChannelID', $ChannelID);
		$this->assign('Action', __URL__.'/saveModify');
		$this->assign('Group', $Group);
		$this->assign('Attribute', $Attribute);
		$this->display();
	}
	
	function saveModify(){
		header("Content-Type:text/html; charset=utf-8");
		unset($_POST['AlbumTitle'], $_POST['AlbumPicture'], $_POST['AlbumDescription']);
		$n = count($_POST);
		foreach ($_POST as $k=>$v){
			if( is_array($v) ){
				$_POST[$k] = implode(',', $v);
			}
		}
		
		//Html存在，并且ChannelName不为空在自动生成拼音文件名（单页频道不生成）
		if( isset($_POST['Html']) && empty($_POST['Html'])  && !empty($_POST['ChannelName']) ){
			$_POST['Html'] = yd_pinyin( $_POST['ChannelName'] );
		}
		if( !isset($_POST['ReadLevel']) ) $_POST['ReadLevel'] = '';
		if( !isset($_POST['f1']) ) $_POST['f1'] = '';
		if( !isset($_POST['f2']) ) $_POST['f2'] = '';
		if( !isset($_POST['f3']) ) $_POST['f3'] = '';
		
		$c = D('Admin/Channel');
		if( $c->create() ){
			YdCache::deleteChannelHtml( $_POST['Html'] ); //保存频道时，清除频道缓存
			if($GLOBALS['Config']['AUTO_UPLOAD_ENABLE']==1 && stripos($c->ChannelContent , '<img') !== false ){
				//上传远程图片有，需要同步更新编辑器内容
				$temp = yd_upload_content($c->ChannelContent);
				$c->ChannelContent = $temp[2];
				if($c->save() === false){
					$this->ajaxReturn(null, '修改失败!' , 0);
				}else{
					//需要做是否启用自动上传远程图片判断 0:远程地址，1：本地地址
					$this->ajaxReturn($temp[0], $temp[1] , 1);
				}
			}else{
				if($c->save() === false){
					$this->ajaxReturn(null, '修改频道失败!' , 0);
				}else{
					YdCache::writeConfig(); //清除频道缓存
					WriteLog("ID:".$_POST['ChannelID']);
					$this->ajaxReturn(null, '修改频道成功!' , 1);
				}
			}
		}else{
			$this->ajaxReturn(null, $c->getError() , 0);
		}
	}
	
	function del(){
		header("Content-Type:text/html; charset=utf-8");
		$c = D('Admin/Channel');
		$ChannelID = $_GET["ChannelID"];
		$data = "#t$ChannelID";
		if( !is_numeric($ChannelID) ){
			$this->ajaxReturn($data, '参数非法!' , 3);
		}
		
		if( $c->hasChildChannel($ChannelID) ){
			$this->ajaxReturn($data, '当前频道有子频道,请先删除子频道!' , 2);
		}
		
		if( $c->hasData($ChannelID) ){
			$this->ajaxReturn($data, '当前频道有数据,请先删除频道所有数据!' , 2);
		}
		
		//删除操作
		$fileToDel = $c->getAttachment($ChannelID);
		if( $c->safeDelChannel($ChannelID) ){
			batchDelFile($fileToDel);
			YdCache::writeConfig(); //清除频道缓存
			WriteLog("ID:$ChannelID");
			$this->ajaxReturn($data, '删除频道成功!' , 1);
		}else{
			$this->ajaxReturn($data, '删除频道失败!' , 0);
		}
	}

	function getSpecial(){
		$ChannelID = $_GET['ChannelID'];
		if( is_numeric($ChannelID) ){
			$s = D('Admin/Special');
			$SpecialInfo = $s->getSpecial( array('IsEnable'=>1) );
			$option = "<optgroup label='请选择所属专题（按Ctrl+左键可进行多选）'>";
			foreach($SpecialInfo as $key=>$value){
				$v = $value['SpecialID'];
				$t = $value['SpecialName'];
				$option .= "<option value='$v'>$t</option>";
			}
			$option .= '</optgroup>';
			$this->ajaxReturn(null, $option , 1);
		}
	}
	
	/**
	 * 单页频道
	 */
	function single(){
		header("Content-Type:text/html; charset=utf-8");
		
		$ChannelID = $_GET['ChannelID'];
		if( !is_numeric($ChannelID) ){
			alert("非法参数", __URL__.'/single');
		}

		//模型属性信息==============================================
		$c = D('Admin/Channel');
		$ChannelInfo = $c->find( $ChannelID );
		
		$m = D('Admin/Attribute');
		$Attribute = $m->getAttribute($ChannelInfo['ChannelModelID']);
		$Group = $m->getGroup($ChannelInfo['ChannelModelID']);
		
		for($n = 0; $n < count($Attribute); $n++){
		   if( $this->IsSelectedAttribute( $Attribute[$n]['DisplayType'] ) ){
				if ( $Attribute[$n]['DisplayType'] == 'channelselect'){
					$Attribute[$n]['SelectedValue'] = $ChannelInfo[ 'ChannelID' ]; //获取频道设置值
					$Attribute[$n]['FirstValue'] = "0"; //FirstValue
					$Attribute[$n]['FirstText'] = "作为主频道"; //FirstText
				}else if($Attribute[$n]['DisplayType'] == 'membergroupcheckbox'){ //会员分组checkbox
					$Attribute[$n]['DisplayValue'] = $ChannelInfo[ $Attribute[$n]['FieldName'] ];
				}else{
					$Attribute[$n]['SelectedValue'] = $ChannelInfo[ $Attribute[$n]['FieldName'] ]; //获取频道设置值
				}
			}else{
				$Attribute[$n]['DisplayValue'] = $ChannelInfo[ $Attribute[$n]['FieldName'] ];
			}
		}
		$Attribute = parent::parseAttribute($Attribute);  //解析属性信息
		//======================================================
		$this->assign('Action', __URL__.'/saveModify');
		$this->assign('ChannelID', $ChannelID);
		$this->assign('ChannelName', $ChannelInfo['ChannelName']);
		$this->assign('Group', $Group);
		$this->assign('Attribute', $Attribute);
		$this->display();
	}
	
	/**
	 * 链接频道
	 */
	function link(){
		header("Content-Type:text/html; charset=utf-8");
	
		$ChannelID = $_GET['ChannelID'];
		if( !is_numeric($ChannelID) ){
			alert("非法参数", __URL__.'/Save');
		}
	
		//模型属性信息==============================================
		$c = D('Admin/Channel');
		$ChannelInfo = $c->find( $ChannelID );
	
		$m = D('Admin/Attribute');
		$Attribute = $m->getAttribute($ChannelInfo['ChannelModelID']);
		$Group = $m->getGroup($ChannelInfo['ChannelModelID']);
	
		for($n = 0; $n < count($Attribute); $n++){
			if( $this->IsSelectedAttribute( $Attribute[$n]['DisplayType'] ) ){
					$Attribute[$n]['SelectedValue'] = $ChannelInfo[ $Attribute[$n]['FieldName'] ]; //获取频道设置值
			}else{
				$Attribute[$n]['DisplayValue'] = $ChannelInfo[ $Attribute[$n]['FieldName'] ];
			}
		}
		$Attribute = parent::parseAttribute($Attribute);  //解析属性信息
		//======================================================
		$this->assign('Action', __URL__.'/saveModify');
		$this->assign('ChannelID', $ChannelID);
		$this->assign('ChannelName', $ChannelInfo['ChannelName']);
		$this->assign('Group', $Group);
		$this->assign('Attribute', $Attribute);
		$this->display();
	}
	
	/**
	 * 保存所有修改
	 */
	function saveAll(){
		$data = array(
				"ChannelID" => $_POST['ChannelID'],
				"ChannelName" => $_POST['ChannelName'],
				"Html" => $_POST['Html'],
				"ChannelOrder" => $_POST['ChannelOrder'],
				"PageSize" => $_POST['PageSize'],
				"ChannelSName" => $_POST['ChannelSName'],
				"IndexTemplate" => $_POST['IndexTemplate'],
				"ReadTemplate" => $_POST['ReadTemplate']
		);

		if( count($data['ChannelID']) > 0 ){
			$m = D('Admin/Channel');
			$m->saveAll( $data );
			YdCache::deleteHtml('channel'); //清楚所有频道缓存
			YdCache::deleteHtml('index'); //清楚所有频道缓存
			WriteLog();
		}
		redirect(__URL__."/index");
	}
	
	/**
	 * 清除频道缓存
	 */
	function clearCache(){
		YdCache::writeConfig();
		$this->ajaxReturn(null, '清除频道缓存成功!' , 1);
	}
}
?>